import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
import iView from 'iview'
import {
  setToken,
  getToken,
  setTitle
} from '@/libs/util'
import config from '@/config'
import storage from '@/libs/storage';
const {
  homeName
} = config

Vue.use(Router)
const router = new Router({
  routes,
  base: process.env.NODE_ENV === 'production'
    ? '/store/'
    : '/store/',
  mode: 'history'
  // mode: 'hash'
})
const LOGIN_PAGE_NAME = 'login'
const REGISTER_PAGE_NAME = 'register'
const PASSWORD_PAGE_NAME = 'password'
const SELECT_STORE = 'selectStore'
// const turnTo = (to, access, next) => {
//   if (canTurnTo(to.name, access, routes)) next() // 有权限，可访问
//   else next({ replace: true, name: 'error_401' }) // 无权限，重定向到401页面
// }
const turnTo = (to, access, next) => {
  if (access) next() // 有权限，可访问
  else {
    next({
      replace: true,
      name: 'error_401'
    })
  } // 无权限，重定向到401页面
}

router.beforeEach((to, from, next) => {
  iView.LoadingBar.start()
  const userLoginType = localStorage.getItem('userLoginType');

  if (to.name == LOGIN_PAGE_NAME || to.name == REGISTER_PAGE_NAME || to.name == PASSWORD_PAGE_NAME) {
    // 要跳转的是登录页或者注册页或者找回密码页
    if (userLoginType) {
      // 已经确定登录类型
      next({
        name: homeName // 跳转到homeName页
      })
    } else {
      // 未确定登录类型
      next();
    }
  } else {
    // 要跳转的是需登录才可展示页面
    if (userLoginType) {
      // 已经确定登录类型
      if (to.name == 'vip') {
        let url = to.matched[0].meta.href;
        window.open(`${url}`);
        next(false)
        iView.LoadingBar.finish()
      } else {
        next();
      }
    } else {
      // 未确定登录类型
      let token = getToken()
      if (token) {
        // 已经用户登录了，但没有确定登录类型
        if (to.name == SELECT_STORE) {
          // 跳转的是选择门店列表页
          next();
        }
      } else {
        next({
          name: LOGIN_PAGE_NAME // 跳转到登录页
        })
      }
    }
  }
})

router.afterEach(to => {
  setTitle(to, router.app)
  iView.LoadingBar.finish()
  window.scrollTo(0, 0)
})

export default router
